<template>
  <q-page class="page">
    <header class="q-pa-md fixed-top-left full-width bg-white" style="z-index: 20;">
      <div style="font-size: 18px; margin-top: 40px">已为您成功匹配以下机构</div>
      <div class="q-mt-xs" style="font-weight: bold; font-size: 16px">
        点击下方<span style="color: red; font-size: 18px"> 立即申请 </span>获取您的专属额度
      </div>
    </header>
    <div style="height: 130px"></div>

    <section class="q-pa-md">
      <div class="mechanism-card q-mt-md">
        <div class="q-pa-md">
          <div class="mark">
            <div class="mark-text">当前申请</div>
            <div class="flex justify-end q-mt-sm">
              <img src="~/assets/images/public/ok_select.png" style="width: 16px" />
            </div>
          </div>
          <div class="flex items-center">

            <div v-if="!orderItemTop" class="center q-mr-xs">
              <img
                src="~/assets/images/public/zhonjiaxing_logo.png"
                style="width: 25px; border-radius: 99999px"
              />
            </div>
            <div v-else-if="orderItemTop.companyLogo" class="center q-mr-xs">
              <img :src="orderItemTop.companyLogo" style="width: 25px; border-radius: 99999px" />
            </div>
            <div class="text-weight-bold">
              {{ orderItemTop?.companyName ?? '北京中佳信科技发展有限公司' }}
            </div>
          </div>
          <div class="text-weight-bold" style="font-size: 16px; margin-top: 10px">
            {{ orderItemTop?.companyTitle ?? '最高可借186,800元' }}
          </div>
          <div style="color: #999; font-size: 13px" class="q-mt-xs">
            {{ orderItemTop?.companySubTitle ?? '年利率(单利)6.94%~23.73%' }}
          </div>
        </div>
        <div v-if="!!orderItemTop?.protocolUrl" class="">
          <iframe
            :src="orderItemTop.protocolUrl"
            style="border: 0; margin: 0; padding: 0; outline: none; height: 160px"
            class="full-width block"
          ></iframe>
        </div>
      </div>

      <div class="select-card q-pa-md q-mt-md" v-if="!!orderItemSelectList?.length">
        <div class="flex items-center justify-between">
          <div style="font-size: 14px">
            选择机构越多，<span style="color: #fcba72">获得额度机会更高</span>
          </div>

          <div class="flex items-center">
            <div class="q-mr-xs">全选</div>
            <div class="center" @click="selectAllHandler">
              <img v-if="!isSelectAll" src="~/assets/images/public/nu_select_op.png" style="width: 16px" />
              <img v-else src="~/assets/images/public/ok_select.png" style="width: 16px" />
            </div>
          </div>
        </div>

        <div class="progress-box" style="margin-top: 14px">
          <div class="progress-bg"></div>
          <div class="progress" :style="{ width: `${progressOneAPIB}%` }">
            <div class="mark"></div>
          </div>
        </div>

        <div
          v-for="(item, index) in orderItemSelectList"
          :key="index"
          class="list-item q-py-md"
          :class="{ 'q-mt-md': !index }"
        >
          <div class="flex items-center">
            <div v-if="item?.companyLogo" class="center q-mr-xs">
              <img :src="item.companyLogo" style="width: 25px; border-radius: 99999px" />
            </div>
            <div class="text-weight-bold">{{ item.companyName || '' }}</div>
          </div>
          <div class="flex items-center justify-between">
            <div class="q-mr-sm">
              <div class="text-weight-bold" style="font-size: 16px; margin-top: 10px">
                {{ item.companyTitle || '' }}
              </div>
              <div style="color: #999; font-size: 13px" class="q-mt-xs">{{ item.companySubTitle || '' }}</div>
            </div>
            <div
              @click="orderItemClickHandler(item)"
              class="center"
              :style="
                !orderItemSelectOkList.includes(item) &&
                item.infoType === 'APIB' &&
                okItemList.some((okitem) => okitem.infoType === 'APIB')
                  ? {
                      opacity: 0.4,
                      pointerEvents: 'none',
                    }
                  : {}
              "
            >
              <img
                v-if="orderItemSelectOkList.includes(item)"
                src="~/assets/images/public/ok_select.png"
                style="width: 16px"
              />
              <img v-else src="~/assets/images/public/nu_select_op.png" style="width: 16px" />
            </div>
          </div>
          <div v-if="!!item.protocolUrl" class="q-mt-sm">
            <iframe
              :src="item.protocolUrl"
              style="border: 0; margin: 0; padding: 0; outline: none; height: 160px"
              class="full-width block"
            ></iframe>
          </div>
        </div>
      </div>
    </section>

    <div style="height: 100px"></div>
    <div class="bottom-action-box q-pa-md">
      <q-btn
        label="立即申请"
        padding="none none"
        unelevated
        rounded
        @click="submit"
        class="full-width"
        style="
          background-color: #FFAD13;
          color: #fff;
          padding: 8px 18px !important;
          font-size: 15px;
          font-weight: 600;
        "
      />
    </div>
    <Protocol ref="ProtocolRef" />
  </q-page>
</template>

<script setup lang="ts">
import { feedbackApi } from 'src/api/member';
import { useAppStore } from 'src/stores/app-store';
import { showSuccessToast, showToast } from 'vant';
import { ref, toRaw, unref, watch } from 'vue';
import { useRouter } from 'vue-router';
import Protocol from './dialog/Protocol.vue';
import { useMechanismStore } from 'src/stores/mechanism-store';
import { computed } from 'vue';
import { MatchResultOrderItemList } from 'src/types/matchResult';
import { ProtocolInstance } from './dialog/Protocol';
import { baseApiUrl } from 'src/config/env.config';
import { testMatchResult } from './mock';

const router = useRouter();
const ProtocolRef = ref<ProtocolInstance>();

const matchData = computed(() => {
  return useMechanismStore().matchData;
  // return testMatchResult
});

const orderItemTop = computed(() => {
  if (!matchData.value) return;
  const { orderItemList } = matchData.value;
  if (orderItemList.length < 1) return;
  return orderItemList[0];
});

const orderItemSelectList = computed(() => {
  if (!matchData.value) return;
  const { orderItemList } = matchData.value;
  if (orderItemList.length < 2) return;
  return orderItemList.slice(1, orderItemList.length);
});
// 当前选择申请list
const orderItemSelectOkList = ref<MatchResultOrderItemList[]>([]);

// 当前选择申请list + 必申请item
const okItemList = computed(() => {
  if (matchData.value?.orderItemList?.length && orderItemTop.value) {
    return [orderItemTop.value, ...orderItemSelectOkList.value];
  }
  return [];
});

watch(orderItemSelectList, (val) => {
  orderItemSelectOkList.value = val ? orderItemSelectOkList.value.filter((item) => val.includes(item)) : [];
});

const orderItemClickHandler = (item: MatchResultOrderItemList) => {
  const list = toRaw(unref(orderItemSelectOkList));
  if (list.includes(item)) {
    orderItemSelectOkList.value = list.filter((itemData) => itemData !== item);
  } else {
    if (item.infoType === 'APIB' && okItemList.value.some((item) => item.infoType === 'APIB')) {
      return;
    }
    orderItemSelectOkList.value.push(item);
  }
};

const progress = computed(() => {
  if (!orderItemSelectList.value?.length) return 0;
  const count = orderItemSelectList.value.length;
  const num = orderItemSelectOkList.value.length;
  return +((num / count) * 100).toFixed(0);
});

const selectAllList = computed(() => {
  if (!orderItemSelectList.value?.length) return [];
  if (orderItemTop.value?.infoType === 'APIB') {
    return orderItemSelectList.value.filter((item) => item.infoType !== 'APIB');
  }
  const oneIndex = orderItemSelectList.value.findIndex((item) => item.infoType === 'APIB');
  return orderItemSelectList.value.filter((item, index) => item.infoType !== 'APIB' || index === oneIndex);
});

const progressOneAPIB = computed(() => {
  if (!orderItemSelectList.value?.length) return false;
  const count = selectAllList.value.length;
  const num = orderItemSelectOkList.value.length;
  if (count === 0) return 0;
  return +((num / count) * 100).toFixed(0);
});

const isSelectAll = computed(() => {
  if (!orderItemSelectList.value?.length) return false;
  const count = selectAllList.value.length;
  const num = orderItemSelectOkList.value.length;
  if (count === 0) return false;
  return count === num;
});

const selectAllHandler = () => {
  if (!orderItemSelectList.value) return;
  orderItemSelectOkList.value = !isSelectAll.value ? [...selectAllList.value] : [];
};

const submit = () => {
  const param =
    okItemList.value.length && matchData.value
      ? {
          orderId: matchData.value.orderId,
          itemOrderIds: JSON.stringify(okItemList.value.map((item) => item.orderItemId)),
          approveUrl: okItemList.value.find((item) => item.infoType === 'APIB')?.approveUrl,
        }
      : undefined;
  const getAgreement = () => {
    if (okItemList.value.length && matchData.value) {
      const urlTemp = matchData.value.orderProtocolUrl ?? '';
      console.log(okItemList.value.map((item) => item.orderItemId));
      const ids = okItemList.value.map((item) => item.orderItemId).join('-');
      console.log(ids);
      return `${baseApiUrl}${urlTemp.replace('{}', ids)}`;
    }
    return;
  };
  ProtocolRef.value?.show(getAgreement(), param);
};
</script>

<style lang="scss" scoped>
.bottom-action-box {
  position: fixed;
  bottom: 0;
  left: 0;
  width: 100%;
  background-color: #fff;
  border-top: 1px solid rgba($color: #ccc, $alpha: 0.4);
  box-shadow: rgba(99, 99, 99, 0.2) 0px 0px 1px 0px;
}
.mechanism-card {
  background: #ffffff;
  box-shadow: 0px 1px 6px 0px rgba(0, 0, 0, 0.07);
  background-image: url(src/assets/images/mechanism/card.png);
  background-repeat: no-repeat;
  background-size: 100% auto;
  border-radius: 8px;
  overflow: hidden;
  position: relative;
  .mark {
    position: absolute;
    right: 0;
    top: 0;
    .mark-text {
      background: #FFAD13;
      color: #fff;
      border-radius: 0px 0px 0px 8px;
      font-size: 12px;
      font-weight: bold;
      padding: 2px 10px;
    }
  }
}
.select-card {
  background-color: #ffffff;
  box-shadow: 0px 1px 6px 0px rgba(0, 0, 0, 0.07);
  border-radius: 8px;
  background-image: url(src/assets/images/mechanism/card.png);
  background-repeat: no-repeat;
  background-size: 100% auto;
  overflow: hidden;
}

.progress-box {
  $height: 14px;
  height: $height;
  position: relative;
  border-radius: 99999px;
  overflow: hidden;
  .progress-bg {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    border-radius: 99999px;
    background-color: #ffeee5;
  }
  .progress {
    position: absolute;
    top: 0;
    left: 0;
    height: 100%;
    transition-duration: 300ms;
    border-radius: 99999px;
    background-color: #FFAD13;
    .mark {
      position: absolute;
      width: $height;
      height: $height;
      right: 0;
      top: 0;
      background: url(src/assets/images/mechanism/icon1.png) no-repeat;
      background-size: 100% 100%;
    }
  }
}

.list-item {
  border-bottom: 1px solid rgba($color: #d8d8d8, $alpha: 0.5);
  &:nth-last-child(1) {
    border-bottom: none;
  }
}
</style>
